package net.qiqb.core.domain.event.sender;

import lombok.extern.slf4j.Slf4j;
import net.qiqb.core.domain.event.DomainEvent;
import net.qiqb.core.domain.event.DomainEventPersistence;
import net.qiqb.core.domain.event.receiver.DomainEventReceiver;
import net.qiqb.core.domain.event.receiver.ReceiveAckResp;

import java.util.List;

@Slf4j
public class DefaultDomainEventSender implements DomainEventSender {

    private final DomainEventPersistence persistence;

    private final DomainEventReceiver domainEventReceiver;

    public DefaultDomainEventSender(DomainEventPersistence persistence, DomainEventReceiver domainEventReceiver) {
        this.persistence = persistence;
        this.domainEventReceiver = domainEventReceiver;
    }

    @Override
    public void sending(DomainEvent event) {
        // todo 后面需要异步发送

        // 更新事件数据库是否能从初始状态 ready 更新为  sending 成功，表示抢到发送权
        final boolean lock = persistence.tryBeginSend(event.getId());
        //
        if (lock) {
            // 直接调用接受方接受事件。如果是本地，直接使用本地调用
            final List<ReceiveAckResp> ackResp = domainEventReceiver.receive(event);
            persistence.updateSend(event.getId());
            // 保存接受服务到数量信息

        } else {
            log.info("尝试发送事件失败");
        }
    }
}
